<template>
  <p-card :bordered="false">
    <div class="box-title">工单条码生成</div>
    <div class="box-params">
      <p-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <p-row :gutter="24">
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-model-item
              ref="workOrderIndex"
              label="生产工单"
              prop="workOrderIndex"
            >
              <p-select
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                v-model="form.workOrderIndex"
                @change="workOrderSelectedChange"
              >
                <p-select-option
                  :value="index"
                  v-for="(item, index) in workOrderList"
                  :key="index"
                  >{{ item.productionno }}</p-select-option
                >
              </p-select>
            </p-form-model-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-model-item ref="mcode" label="产品编码">
              <p-input disabled :value="form.mcode"></p-input>
            </p-form-model-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-model-item ref="mname" label="产品名称">
              <p-input disabled :value="form.mname"></p-input>
            </p-form-model-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-model-item ref="planqty" label="工单数量">
              <p-input disabled :value="form.planqty"></p-input>
            </p-form-model-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-model-item ref="adjDt" label="调整日期">
              <p-date-picker
                :format="'YYYY-MM-DD'"
                v-model="form.adjDt"
                :default-value="moment()"
                @change="onChange"
              />
            </p-form-model-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24" v-if="form.orderType == 7">
            <p-form-model-item ref="workOrderIndex" label="供应商编码">
              <p-input disabled :value="form.custno"></p-input>
            </p-form-model-item>
          </p-col>

          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <p-form-model-item
              ref="ruleIds"
              label="条码规则"
              prop="ruleIds"
            >
              <p-select  mode="multiple" v-model="form.ruleIds" @change="handleChange">
                <p-select-option
                  :value="item.id"
                  v-for="(item, index) in mesBcRuleList"
                  :key="index"
                  >{{ item.ruleName }}
                </p-select-option>
              </p-select>
            </p-form-model-item>
          </p-col>

          <p-col :xl="2" :lg="7" :md="8" :sm="24">
            <p-button
              type="primary"
              @click="showModal"
              style="margin-bottom: 20px"
            >
              Start
            </p-button>
          </p-col>
        </p-row>
      </p-form-model>
    </div>
    <div class="box-title" style="margin-top: 20px">条码明细</div>
    <div class="box-table">
      <table border="1">
        <tr v-for="(item, index) in codeDetail" :key="index">
          <td v-for="(ele, i) in item" :key="i">
            <p-tooltip placement="top">
              <template slot="title" v-if="ele.mac">
                <span>{{ ele.mac }}</span>
              </template>
              <span class="box-table-text">{{ ele.barcode }}</span>
            </p-tooltip>
          </td>
        </tr>
      </table>
    </div>

    <p-modal
      title="'提示'"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p>是否生成条码</p>
    </p-modal>
  </p-card>
</template>

<script type="text/javascript">
import {
  postAction,
  getAction,
  deleteAction,
  api,
  putAction,
} from "@/api/manage";
import moment from "moment";

export default {
  data() {
    return {
      codeDetail: [],
      visible: false,
      confirmLoading: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      workOrderList: [],
      mesBcRuleList: [],
      other: "",
      form: {
        produceNo: "",
        orderType: "",
        custno: "",
        mcode: "", // 产品编码
        mname: "", // 产品名称
        planqty: "", // 工单数量
        adjDt: moment(), // 调整日期
        workOrderIndex: "",
        ruleIds: [],
        mclassid: '',  // 物料类型
        processCoding: '',  // 工艺路线code
        processVersion: '',  // 工艺路线版本
      },
      isStartButonDisabled: false,
      rules: {
        workOrderIndex: [
          { required: true, message: "请选择生产工单", trigger: "blur" },
        ],
        ruleIds: [
          { required: true, message: "请选择条码规则", trigger: "blur" },
        ],
      },
      url: {
        mesBcRuleList: "/mes-code/mesBcRule/allByCodeType", // 规则列表
        workOrderList: "/pmc-plan/productionno/query", // 生成工单列表
        start: "/mes-code/mesBcProduce/codeProduce", //生成条码
        mesBcProDetail: "/mes-code/mesBcPro/detail",
      },
    };
  },
  mounted() {
    this.getWorkOrderList();
    this.getRuleCodeValue();
  },
  methods: {
    moment,

    // 下拉框筛选
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },

    workOrderSelectedChange(index) {
      const workOrderList = this.workOrderList[index];
      this.form.orderType = workOrderList.orderType;
      this.form.custno = workOrderList.lineno;
      this.form.mcode = workOrderList.mcode;
      this.form.mname = workOrderList.mname;
      this.form.planqty = workOrderList.planqty;
      this.form.mclassid = workOrderList.mclassid;
      this.form.processCoding = workOrderList.processCoding;
      this.form.processVersion = workOrderList.processVersion;

      this.getMesBcRuleList(workOrderList.mcode);
    },

    getMesBcProDetail() {
      const params = {
        barcodeType: 0,
        barcodeProduceNo: this.form.produceNo,
      };
      getAction(this.url.mesBcProDetail, params).then((res) => {
        if (res.success) {
          const num = 5;
          let arr = [];
          res.data.forEach((val, index) => {
            let divideFlag = Math.floor(index / num);
            arr[divideFlag] || (arr[divideFlag] = []);
            arr[divideFlag].push(val);
          });
          this.codeDetail = arr;
        }
      });
    },

    getMesBcRuleList(mcode) {
      const params = {
        codeType: 0,
        mcode,
      };
      getAction(this.url.mesBcRuleList, params).then((res) => {
        console.log("res", res);
        if (res.success) {
          this.mesBcRuleList = res.data;
          // this.mesBcRuleList = new Array(10).fill(null).map(ele => {
          //   ele = JSON.parse(JSON.stringify(res.data[0]))
          //   ele.id = 1000 * Math.random()
          //   return ele
          // });
          // console.log(this.mesBcRuleList);
          
        }
      });
    },

    getRuleCodeValue() {
      let param = {
        rules: [{ ruleCode: "bc_produce_no", columnName: "bc_produce_no" }],
      };
      putAction(api.ruleBaseURL, param).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          console.log("生成的编码：" + res.data.bc_produce_no);
          this.form.produceNo = res.data["bc_produce_no"];
          this.isStartButonDisabled = false;
        }
      });
    },
    getWorkOrderList() {
      const params = {
        generatePrint: 0,
        // generatePrint: 1
        isPublic: 1,
      };
      getAction(this.url.workOrderList, params).then((res) => {
        if (res.success) {
          console.log(res);
          this.workOrderList = res.data;
        }
      });
    },
    showModal() {
      this.visible = true;
    },
    // 生成条码
    handleOk(e) {
      this.$refs.ruleForm.validate((valid) => {
        console.log(123);
        console.log(valid);

        if (valid) {
          console.log(888);

          this.confirmLoading = true;
          const workOrderInfo = this.workOrderList[this.form.workOrderIndex];

          let barcodeRule = "";
          this.mesBcRuleList.forEach((ele) => {
            if (ele.id == this.form.ruleIds) {
              barcodeRule = ele.ruleName;
            }
          });

          let params = {
            barcodeType: 0,
            qty: workOrderInfo.planqty || Math.floor(Math.random() * 100),
            productionno: workOrderInfo.productionno,
            orderType: workOrderInfo.orderType,
            barcodeProduceNo: this.form.produceNo,
            mcode: this.form.mcode,
            mname: this.form.mname,
            custno: workOrderInfo.lineno, // 供应商
            adjDt: this.form.adjDt, // 调整日期
            ruleIds: this.form.ruleIds,
            barcodeRule,
          };

          postAction(this.url.start, params).then((res) => {
            if (res.success) {
              this.isStartButonDisabled = true;
              this.getMesBcProDetail();
              this.getRuleCodeValue();

              // const workOrderList = this.workOrderList[index]
              // this.getMesBcRuleList(workOrderList.mcode);
            } else {
              this.$message.warning(res.msg);
              this.confirmLoading = false;
            }
            this.visible = false;
            this.confirmLoading = false;
          });
        } else {
          this.visible = false;
          return false;
        }
      });
    },
    handleCancel(e) {
      console.log("Clicked cancel button");
      this.visible = false;
    },
  },
  components: {},
};
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>
<style lang="less" scoped>
.box-title {
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
  padding-left: 20px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}
.box-params {
  padding-top: 20px;
}
.box-table {
  padding-top: 20px;
  table {
    width: 100%;
    tr {
      td {
        height: 40px;
        line-height: 40px;
        text-align: center;
        width: 20%;
        .box-table-text {
          cursor: pointer;
        }
      }
    }
  }
}
.poros-form .poros-form-item {
  min-height: 60px;
}
</style>
